package ans.p407;

import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * #      407
 * 名称   接雨水 II
 * 链接   https://leetcode-cn.com/problems/trapping-rain-water-ii
 * 题解   [98](https://leetcode-cn.com/problems/trapping-rain-water-ii/solution)
 * 通过率 46.8%
 * 难道   困难
 */
class Solution {
    /**
     * 抽象接雨水模板
     *
     * @param length 长度
     * @param getNum 获取值的方法
     * @param setNum 赋值方法
     */
    public void trap(int length, Function<Integer, Integer> getNum, BiConsumer<Integer, Integer> setNum) {
        int left = 0, right = length;
        int maxLeft = 0, maxRight = 0;
        while (left < right) {
            Integer tl = getNum.apply(left);
            Integer tr = getNum.apply(right);
            if (tl < tr) {

                maxLeft = Math.max(maxLeft, tl);
                setNum.accept(left, maxLeft - tl);
                left++;
            } else {

                maxRight = Math.max(maxRight, tr);
                setNum.accept(right, maxRight - tr);
                right--;
            }
        }
    }
    //todo
    public int trapRainWater(int[][] heightMap) {
        int[][] res = new int[heightMap.length][heightMap[0].length];
        int[] ans = new int[]{0};
        //横向取
        for (int i = 0; i < heightMap.length; i++) {
            final int index = i;
            trap(heightMap[0].length - 1, (j) -> heightMap[index][j], (j, num) -> {

                res[index][j] = num;
            });
        }
        //纵向取 ans记录最小值
        for (int i = 0; i < heightMap[0].length; i++) {
            final int index = i;
            trap(heightMap.length - 1, (j) -> heightMap[j][index], (j, num) -> {

                ans[0] += Math.min(num, res[j][index]);
            });
        }
        return ans[0];
    }

    public static void main(String[] args) {

    }
}
